from fastapi import HTTPException
from config import Config
from utils import (
    convert_params, 
    service, 
    get_etc_transaction_summary, 
    process_analysis_and_chart, 
    call_etc_service_common,
    extract_merchant_keyword_from_history,
    get_user_merchants, 
    safe_extract_merchant_name
)
from models import ETCSettParams
from chat_history import chat_history_manager
import logging
import time
from typing import Optional
from utils import analyze_data, TrendAnalyzer, should_include_analysis, should_include_chart
# 生成Excel数据的函数
def generate_excel_data(transactions: list, merchant_name_mapping: dict, start_date: str, end_date: str) -> dict:
    """
    生成供前端生成Excel的JSON数据
    
    Args:
        transactions: 交易数据列表（包含所有交易类型）
        merchant_name_mapping: 商户名称映射字典
        start_date: 开始日期
        end_date: 结束日期
        
    Returns:
        dict: Excel数据的JSON结构
    """
    if not transactions:
        return {
            "title": "场库日交易报表",
            "dateRange": f"{start_date} - {end_date}",
            "columns": [
                "停车场名称", "交易日期", "交易笔数", "交易金额", "退款笔数", 
                "退款金额", "交易手续费", "应结算金额"
            ],
            "data": []
        }
    
    # 格式化日期范围
    formatted_start_date = f"{start_date[:4]}/{start_date[4:6]}/{start_date[6:8]}" if len(start_date) == 8 else start_date
    formatted_end_date = f"{end_date[:4]}/{end_date[4:6]}/{end_date[6:8]}" if len(end_date) == 8 else end_date
    
    # 按商户和日期分组数据
    merchant_date_data = {}
    
    for transaction in transactions:
        merchant_id = transaction.get('subStation', '')
        merchant_name = merchant_name_mapping.get(merchant_id, f"商户ID: {merchant_id}")
        trade_date = transaction.get('stlmDate', '')
        trade_type = transaction.get('tradeType', '')
        
        # 创建商户和日期的组合键
        key = f"{merchant_id}_{trade_date}"
        
        if key not in merchant_date_data:
            merchant_date_data[key] = {
                "merchant_id": merchant_id,
                "merchant_name": merchant_name,
                "trade_date": trade_date,
                "deducteTrade": {
                    "countNum": 0,
                    "sumFee": 0,
                    "sumHanding": 0,
                    "sumDeductFee": 0
                },
                "refundTrade": {
                    "countNum": 0,
                    "sumFee": 0,
                    "sumHanding": 0,
                    "sumDeductFee": 0
                }
            }
        
        # 根据交易类型累加数据
        if trade_type == 'deducteTrade':
            # 扣款交易（消费）
            merchant_date_data[key]["deducteTrade"]["countNum"] += int(transaction.get('countNum', 0))
            merchant_date_data[key]["deducteTrade"]["sumFee"] += float(transaction.get('sumFee', 0)) / 100
            merchant_date_data[key]["deducteTrade"]["sumHanding"] += float(transaction.get('sumHanding', 0)) / 100
            merchant_date_data[key]["deducteTrade"]["sumDeductFee"] += float(transaction.get('sumDeductFee', 0)) / 100
        elif trade_type == 'refundTrade':
            # 退款交易
            merchant_date_data[key]["refundTrade"]["countNum"] += int(transaction.get('countNum', 0))
            merchant_date_data[key]["refundTrade"]["sumFee"] += float(transaction.get('sumFee', 0)) / 100
            merchant_date_data[key]["refundTrade"]["sumHanding"] += float(transaction.get('sumHanding', 0)) / 100
            merchant_date_data[key]["refundTrade"]["sumDeductFee"] += float(transaction.get('sumDeductFee', 0)) / 100
    
    # 构建最终数据
    excel_data_list = []
    merchant_subtotals = {}
    
    # 按商户和日期生成合并后的记录
    for key, data in sorted(merchant_date_data.items(), key=lambda x: (x[1]["merchant_id"], x[1]["trade_date"])):
        merchant_id = data["merchant_id"]
        
        # 创建合并记录，将扣款交易和退款交易合并到一行
        record = {
            "current_merchant_name": data["merchant_name"],
            "stlmDate": data["trade_date"],
            "countNum": str(data["deducteTrade"]["countNum"]),
            "sumFee": f"{data['deducteTrade']['sumFee']:.2f}",
            "refundCount": str(data["refundTrade"]["countNum"]),
            "refundAmount": f"{data['refundTrade']['sumFee']:.2f}",
            "sumHanding": f"{data['deducteTrade']['sumHanding'] + data['refundTrade']['sumHanding']:.2f}",
            "sumDeductFee": f"{data['deducteTrade']['sumDeductFee'] + data['refundTrade']['sumDeductFee']:.2f}"
        }
        excel_data_list.append(record)
        
        # 更新商户小计
        if merchant_id not in merchant_subtotals:
            merchant_subtotals[merchant_id] = {
                "merchant_name": data["merchant_name"],
                "countNum": 0,
                "sumFee": 0,
                "refundCount": 0,
                "refundAmount": 0,
                "sumHanding": 0,
                "sumDeductFee": 0
            }
        
        # 累加消费数据到小计
        merchant_subtotals[merchant_id]["countNum"] += data["deducteTrade"]["countNum"]
        merchant_subtotals[merchant_id]["sumFee"] += data["deducteTrade"]["sumFee"]
        merchant_subtotals[merchant_id]["refundCount"] += data["refundTrade"]["countNum"]
        merchant_subtotals[merchant_id]["refundAmount"] += data["refundTrade"]["sumFee"]
        merchant_subtotals[merchant_id]["sumHanding"] += data["deducteTrade"]["sumHanding"] + data["refundTrade"]["sumHanding"]
        merchant_subtotals[merchant_id]["sumDeductFee"] += data["deducteTrade"]["sumDeductFee"] + data["refundTrade"]["sumDeductFee"]
    
    # 按商户添加小计
    for merchant_id, subtotal in merchant_subtotals.items():
        subtotal_record = {
            "summaryType": "subtotal",
            "current_merchant_name": f"{subtotal['merchant_name']}小计",
            "stlmDate": "",
            "countNum": str(subtotal["countNum"]),
            "sumFee": f"{subtotal['sumFee']:.2f}",
            "refundCount": str(subtotal["refundCount"]),
            "refundAmount": f"{subtotal['refundAmount']:.2f}",
            "sumHanding": f"{subtotal['sumHanding']:.2f}",
            "sumDeductFee": f"{subtotal['sumDeductFee']:.2f}"
        }
        excel_data_list.append(subtotal_record)
    
    # 计算总计
    total_count = sum(subtotal["countNum"] for subtotal in merchant_subtotals.values())
    total_amount = sum(subtotal["sumFee"] for subtotal in merchant_subtotals.values())
    total_refund_count = sum(subtotal["refundCount"] for subtotal in merchant_subtotals.values())
    total_refund_amount = sum(subtotal["refundAmount"] for subtotal in merchant_subtotals.values())
    total_fee = sum(subtotal["sumHanding"] for subtotal in merchant_subtotals.values())
    total_deduct_fee = sum(subtotal["sumDeductFee"] for subtotal in merchant_subtotals.values())
    
    # 添加总计
    total_record = {
        "summaryType": "total",
        "current_merchant_name": "总计",
        "stlmDate": "",
        "countNum": str(total_count),
        "sumFee": f"{total_amount:.2f}",
        "refundCount": str(total_refund_count),
        "refundAmount": f"{total_refund_amount:.2f}",
        "sumHanding": f"{total_fee:.2f}",
        "sumDeductFee": f"{total_deduct_fee:.2f}"
    }
    excel_data_list.append(total_record)
    
    return {
        "title": "场库日交易报表",
        "dateRange": f"{formatted_start_date} - {formatted_end_date}",
        "columns": [
            "停车场名称", "交易日期", "交易笔数", "交易金额", "退款笔数", 
            "退款金额", "交易手续费", "应结算金额"
        ],
        "data": excel_data_list
    }

# 处理ETC结算数据
async def process_etc_sett_data(user_query: str, phone_number: str, conversation_id: str, include_analysis: Optional[bool] = None, include_chart: Optional[bool] = None, timeout: int = 60, params: Optional[dict] = None) -> dict:
    start_time = time.time()
    logging.info(f"[步骤5-ETC结算数据处理] 开始处理ETC结算数据")
    
    # 获取对话历史
    history = chat_history_manager.get_history(conversation_id)
    logging.info(f"[对话管理] 获取到历史消息数量: {len(history)}")
    
    # 转换用户查询为API参数，并传递历史对话数据
    if params is None:
        params = await convert_params(user_query, "etc_sett", phone_number, history)
        
        # 检查是否为模糊关键词处理结果
        if isinstance(params, dict) and params.get('is_ambiguous_keyword'):
            # 如果是模糊关键词，直接返回反问消息
            logging.info(f"[参数转换] 检测到模糊关键词，返回反问消息")
            ambiguous_response = params.get('ambiguous_response', {})
            
            # 保存对话记录到本地对话ID中
            chat_history_manager.add_message(conversation_id, "user", user_query)
            chat_history_manager.add_message(conversation_id, "assistant", ambiguous_response.get('response_message', ''))
            
            # 获取日期范围（从模糊关键词响应中提取或使用默认值）
            start_date = params.get('startDate', datetime.now().strftime('%Y%m%d'))
            end_date = params.get('endDate', datetime.now().strftime('%Y%m%d'))
            
            # 格式化日期范围
            formatted_start_date = f"{start_date[:4]}/{start_date[4:6]}/{start_date[6:8]}" if len(start_date) == 8 else start_date
            formatted_end_date = f"{end_date[:4]}/{end_date[4:6]}/{end_date[6:8]}" if len(end_date) == 8 else end_date
            
            # 创建商户名称映射（使用默认值）
            merchant_name_mapping = {"default": "停车场"}
            
            # 生成Excel数据（使用空交易数据，但包含正确的小计和总计结构）
            excel_data = generate_excel_data([], merchant_name_mapping, start_date, end_date)
            
            # 构建与普通查询结果一致的返回格式
            result = {
                "user_query": user_query,
                "summary": ambiguous_response.get('response_message', ''),
                "records": [],
                "download_links": [],
                "extend_question": "",
                "excel_data": excel_data
            }
            
            return {
                "answer": ambiguous_response.get('response_message', ''),
                "conversation_id": conversation_id,
                "result": result
            }
        
        # 如果历史对话中包含商户信息，尝试从历史中提取商户ID
        if history and not params.get("subStationIds"):
            try:
                # 从历史对话中提取商户关键词
                merchant_keyword = await extract_merchant_keyword_from_history(history, phone_number)
                if merchant_keyword:
                    # 获取用户可查询商户列表
                    available_merchants = await get_user_merchants(phone_number, return_empty_on_error=True)
                    # 匹配商户ID
                    for merchant in available_merchants:
                        if isinstance(merchant, dict) and merchant.get('merName') == merchant_keyword:
                            params["subStationIds"] = [merchant.get('merId')]
                            logging.info(f"[参数转换] 从历史对话中提取到商户ID: {params['subStationIds']}")
                            break
            except Exception as e:
                logging.error(f"[参数转换] 从历史对话中提取商户ID失败: {str(e)}")
    
    logging.info(f"[参数转换] ETC结算查询参数: {params}")
    
    # 提取参数并验证
    try:
        # 提取subStationIds参数
        sub_station_ids = params.get("subStationIds", [])
        
        # 检查subStationIds是否为空列表
        if sub_station_ids is not None and isinstance(sub_station_ids, list) and len(sub_station_ids) == 0:
            logging.error(f"[参数验证] ETC结算参数验证失败: subStationIds为空列表")
            raise HTTPException(status_code=400, detail="请指定要查询的结算站点，不能查询全量数据")
        
        validated_params = ETCSettParams(
            startDate=params.get("startDate", ""),
            endDate=params.get("endDate", ""),
            subStationIds=sub_station_ids
        )
        logging.info(f"[参数验证] ETC结算参数验证通过: {validated_params.model_dump()}")
    except Exception as e:
        logging.error(f"[参数验证] ETC结算参数验证失败: {str(e)}")
        raise HTTPException(status_code=400, detail=f"参数验证失败：{str(e)}")
    
    # 提取验证后的参数
    start_date = validated_params.startDate
    end_date = validated_params.endDate
    sub_station_ids = validated_params.subStationIds
    
    # 调用ETC结算数据查询函数
    try:
        summary_data = await get_etc_transaction_summary(
            start_date=start_date,
            end_date=end_date,
            sub_station_ids=sub_station_ids,
            phone_number=phone_number
        )
    except Exception as e:
        logging.error(f"[API调用] ETC结算API调用失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"API调用失败：{str(e)}")
    
    # 确保data是字典类型
    if not isinstance(summary_data, dict):
        logging.error(f"[API调用] ETC结算API返回类型错误，期望字典但得到: {type(summary_data)}")
        raise HTTPException(status_code=500, detail="API返回数据格式错误")
    
    # 获取交易数据（从respData或resultDOS字段）
    transactions = summary_data.get('respData', summary_data.get('resultDOS', []))
    logging.info(f"[API调用] ETC结算数据获取成功: {len(transactions)}条记录")
    
    # 检查API调用是否成功
    code_success = summary_data.get('code') == '10000'
    resp_code_success = summary_data.get('respCode') in [100, '100']  # 同时支持数字和字符串
    
    if not code_success and not resp_code_success:
        error_msg = summary_data.get('msg', summary_data.get('respMsg', '未知错误'))
        logging.error(f"[API错误] ETC结算查询失败: {error_msg}")
        raise HTTPException(status_code=400, detail=f"查询失败：{error_msg}")
    
    # 确保transactions是列表类型
    if not isinstance(transactions, list):
        logging.error(f"[数据处理] ETC结算数据格式错误，期望列表但得到: {type(transactions)}")
        transactions = []
    
    # 过滤交易类型为deducteTrade的记录（用于主要显示）
    original_count = len(transactions)
    all_transactions = transactions.copy()  # 保存所有交易数据用于Excel
    transactions = [t for t in transactions if t.get('tradeType') == 'deducteTrade']
    filtered_count = len(transactions)
    logging.info(f"[数据过滤] 原始记录数: {original_count}, 过滤后记录数: {filtered_count}")
    
    total_count = len(transactions)
    logging.info(f"[数据处理] ETC结算记录数量: {total_count}条")

    # 创建商户名称映射字典
    merchant_name_mapping = {}
    try:
        # 从params中获取手机号和商户ID列表
        user_id = params.get('userId', params.get('phoneNo', ''))
        merchant_ids = params.get('subStationIds', [])
        logging.info(f"[商户名称获取] 开始获取商户名称映射，手机号: {user_id}, 商户ID列表: {merchant_ids}")
        
        if user_id and merchant_ids:
            # 获取用户可查询商户列表
            available_merchants = await get_user_merchants(user_id, return_empty_on_error=True)
            logging.info(f"[商户名称获取] 获取到可查询商户数量: {len(available_merchants)}")
            
            # 构建商户ID到商户名称的映射
            for merchant in available_merchants:
                if isinstance(merchant, dict):
                    # 尝试多种可能的商户ID字段
                    mer_id = merchant.get('merId') or merchant.get('merchantId') or merchant.get('id')
                    if mer_id:
                        merchant_name = safe_extract_merchant_name(merchant)
                        merchant_name_mapping[mer_id] = merchant_name
                        logging.info(f"[商户名称映射] 添加映射: {mer_id} -> {merchant_name}")
            
            # 检查是否所有查询的商户ID都有对应的名称
            for merchant_id in merchant_ids:
                if merchant_id not in merchant_name_mapping:
                    logging.warning(f"[商户名称获取] 未在可查询商户列表中找到匹配的商户ID: {merchant_id}")
                    # 尝试从结算数据中获取商户名称
                    if transactions:
                        for transaction in transactions:
                            if isinstance(transaction, dict) and transaction.get('subStation') == merchant_id:
                                merchant_name_mapping[merchant_id] = f"结算站点ID: {merchant_id}"
                                logging.info(f"[商户名称获取] 从结算数据中获取商户信息: {merchant_id}")
                                break
                    
                    # 如果仍未获取到商户名称，使用默认名称
                    if merchant_id not in merchant_name_mapping:
                        merchant_name_mapping[merchant_id] = f"商户ID: {merchant_id}"
        else:
            logging.warning(f"[商户名称获取] 缺少必要参数，手机号: {user_id}, 商户ID列表: {merchant_ids}")
            # 如果缺少参数，尝试使用第一个可查询商户作为备选
            if user_id:
                try:
                    available_merchants = await get_user_merchants(user_id, return_empty_on_error=True)
                    if available_merchants:
                        first_merchant = available_merchants[0]
                        default_merchant_name = safe_extract_merchant_name(first_merchant)
                        # 为所有可能的商户ID设置默认名称
                        for merchant_id in merchant_ids:
                            merchant_name_mapping[merchant_id] = default_merchant_name
                        logging.info(f"[商户名称获取] 缺少参数时使用第一个可查询商户作为备选: {default_merchant_name}")
                except Exception as e:
                    logging.error(f"[商户名称获取] 获取第一个可查询商户名称失败: {str(e)}")
    except Exception as e:
        logging.error(f"获取商户名称映射失败: {str(e)}")
        # 创建默认映射
        for merchant_id in params.get('subStationIds', []):
            merchant_name_mapping[merchant_id] = f"商户ID: {merchant_id}"

    # 获取do_analysis和do_chart的值，用于后续判断
    do_analysis = include_analysis if include_analysis is not None else should_include_analysis(user_query, "etc_sett")
    do_chart = include_chart if include_chart is not None else should_include_chart(user_query, "etc_sett")
    
    # 构建竖向Markdown表格格式的结果
    if total_count == 0:
        # 尝试扩展查询
        try:
            from utils_1 import enhance_no_data_response
            # 构建原始响应对象
            original_response = {
                "user_query": user_query,
                "summary": "### 未找到符合条件的ETC结算记录",
                "records": [],
                "download_links": []
            }
            
            # 调用扩展查询功能
            enhanced_response = await enhance_no_data_response(
                response=original_response,
                params=params,
                api_path=Config.ETC_SETT_API_PATH,
                query_type="etc_sett",
                service=call_etc_sett_service,
                user_query=user_query
            )
            
            # 如果扩展查询有结果，返回扩展后的响应
            if enhanced_response:
                return enhanced_response
            
            # 如果扩展查询也没有结果，使用原始响应
            result_lines = [f"### 未找到符合条件的ETC结算记录"]
            
        except Exception as e:
            logging.error(f"[扩展查询] ETC结算扩展查询失败: {str(e)}")
            result_lines = [f"### 未找到符合条件的ETC结算记录"]
    else:
        result_lines = [f"### 查询成功，共找到{total_count}条ETC结算记录"]
    
    # 如果用户要求数据分析，则显示数据分析模式的提示信息
    if do_analysis or do_chart:
        result_lines = [f"### 数据分析结果"]
    
    # 创建独立的记录数组
    records = []
    download_links = []
    
    if all_transactions:
        # 按商户和日期分组交易数据
        merchant_date_data = {}
        
        for transaction in all_transactions:
            merchant_id = transaction.get('subStation', '')
            trade_date = transaction.get('stlmDate', '')
            trade_type = transaction.get('tradeType', '')
            
            # 创建商户和日期的组合键
            key = f"{merchant_id}_{trade_date}"
            
            if key not in merchant_date_data:
                merchant_date_data[key] = {
                    "merchant_id": merchant_id,
                    "trade_date": trade_date,
                    "countNum": 0,
                    "sumFee": 0,
                    "sumHanding": 0,
                    "sumDeductFee": 0,
                    "refundCount": 0,
                    "refundAmount": 0
                }
            
            # 根据交易类型累加数据
            if trade_type == 'deducteTrade':
                # 扣款交易
                merchant_date_data[key]["countNum"] += int(transaction.get('countNum', 0))
                merchant_date_data[key]["sumFee"] += float(transaction.get('sumFee', 0)) / 100
                merchant_date_data[key]["sumHanding"] += float(transaction.get('sumHanding', 0)) / 100
                merchant_date_data[key]["sumDeductFee"] += float(transaction.get('sumDeductFee', 0)) / 100
            elif trade_type == 'refundTrade':
                # 退款交易
                merchant_date_data[key]["refundCount"] += int(transaction.get('countNum', 0))
                merchant_date_data[key]["refundAmount"] += float(transaction.get('sumFee', 0)) / 100
                merchant_date_data[key]["sumHanding"] += float(transaction.get('sumHanding', 0)) / 100
                merchant_date_data[key]["sumDeductFee"] += float(transaction.get('sumDeductFee', 0)) / 100
        
        # 添加合并后的记录
        idx = 1
        for key, data in sorted(merchant_date_data.items(), key=lambda x: (x[1]["merchant_id"], x[1]["trade_date"])):
            # 获取当前记录的商户ID
            current_merchant_id = data["merchant_id"]
            
            # 根据商户ID获取对应的商户名称
            if current_merchant_id in merchant_name_mapping:
                current_merchant_name = merchant_name_mapping[current_merchant_id]
            else:
                # 如果映射中没有找到，尝试从商户列表中查找
                current_merchant_name = f"商户ID: {current_merchant_id}"
                if user_id:
                    try:
                        available_merchants = await get_user_merchants(user_id, return_empty_on_error=True)
                        for merchant in available_merchants:
                            if isinstance(merchant, dict):
                                # 尝试多种可能的商户ID字段
                                mer_id = merchant.get('merId') or merchant.get('merchantId') or merchant.get('id')
                                if mer_id == current_merchant_id:
                                    current_merchant_name = safe_extract_merchant_name(merchant)
                                    # 更新映射字典
                                    merchant_name_mapping[current_merchant_id] = current_merchant_name
                                    break
                    except Exception as e:
                        logging.error(f"[记录显示] 获取商户名称失败: {str(e)}")
            
            # 构建单条记录的完整内容
            record_content = []
            record_content.append(f"#### 第{idx}条ETC结算记录")
            record_content.append(f"| 序号 | {idx} |")
            record_content.append("|------|-----|")
            record_content.append(f"| 停车场名称 | {current_merchant_name} |")
            record_content.append(f"| 商户ID | {current_merchant_id} |")
            record_content.append(f"| 交易日期 | {data['trade_date']} |")
            record_content.append(f"| 交易笔数 | {data['countNum']} |")
            record_content.append(f"| 交易金额(元) | {data['sumFee']:.2f} |")
            record_content.append(f"| 退款笔数 | {data['refundCount']} |")
            record_content.append(f"| 退款金额(元) | {data['refundAmount']:.2f} |")
            record_content.append(f"| 交易手续费(元) | {data['sumHanding']:.2f} |")
            record_content.append(f"| 应结算金额(元) | {data['sumDeductFee']:.2f} |")
           
            # 将完整记录内容作为单个字符串添加到records数组
            records.append("\n".join(record_content))
            idx += 1

    # 使用公共函数处理数据分析和趋势图生成
    # 确定分析标题中的商户名称
    analysis_merchant_name = ""
    if merchant_name_mapping:
        # 如果有多个商户，使用第一个商户名称
        first_merchant_id = list(merchant_name_mapping.keys())[0]
        analysis_merchant_name = merchant_name_mapping[first_merchant_id]
    else:
        analysis_merchant_name = "商户"
    
    # 判断是否需要生成多商户对比趋势图
    # 如果查询了多个商户，使用多商户对比模式
    group_field = None
    if len(merchant_name_mapping) > 1:
        group_field = "subStation"  # 使用商户ID字段进行分组
        analysis_merchant_name = "多商户"  # 修改标题为多商户
    
    analysis_result = await process_analysis_and_chart(
        data=summary_data,
        data_list=transactions,
        user_query=user_query,
        analysis_type="etc_sett",
        include_analysis=include_analysis,
        include_chart=include_chart,
        date_field="stlmDate",
        value_field="sumFee",
        title=f'{analysis_merchant_name}ETC交易总金额趋势',
        x_label="清算日期",
        y_label="交易总金额(元)",
        value_converter=lambda x: float(x)/100 if x else 0,  # 将分转换为元
        start_date=start_date,
        end_date=end_date,
        filter_field="tradeType",  # 添加交易类型过滤
        filter_value="deducteTrade",  # 只使用deducteTrade类型的数据作图
        group_field=group_field  # 商户分组字段
    )
    
    trend_data = analysis_result["trend_data"]
    text_analysis = analysis_result["text_analysis"]
    
    # 生成Excel数据
    excel_data = generate_excel_data(all_transactions, merchant_name_mapping, start_date, end_date)

    # 添加调试日志
    logging.info(f"[ETC结算] do_analysis: {do_analysis}, do_chart: {do_chart}")
    logging.info(f"[ETC结算] 有分析结果: {text_analysis is not None}, 有图表数据: {trend_data is not None and 'trend_chart' in trend_data}")

    # 使用传入的conversation_id
    logging.info(f"[对话管理] 使用传入的conversation_id: {conversation_id}")

    # 构建响应对象
    response = {
        "user_query": user_query,
        "summary": result_lines[0] if result_lines else ("数据分析结果" if do_analysis or do_chart else ""),
        "records": records if not (do_analysis or do_chart) else [],  # 分开问时只返回查询数据
        "download_links": download_links if not (do_analysis or do_chart) else [],  # 分开问时只返回下载链接
        "excel_data": excel_data  # 添加Excel数据字段
    }
    
    # 仅在用户没有要求分析或画图时返回趋势分析字段
    if not do_analysis and not do_chart:
        response["extend_question"] = "对数据进行趋势分析和可视化"
    
    # 只有在生成了分析结果时才包含analysis字段
    if text_analysis:
        response["analysis"] = text_analysis
    
    # 只有在生成了趋势图时才包含chart字段
    if trend_data and "trend_chart" in trend_data:
        response["chart"] = trend_data["trend_chart"]
    
    # 添加debug_info字段，与正常发票服务保持一致
    if params.get("debug", False):
        response["debug_info"] = {
            "generated_params": params,
            "target_api_url": f"{Config.ETC_API_BASE_URL}{Config.ETC_SETT_API_PATH}",
            "raw_response": summary_data
        }
    
    end_time = time.time()
    logging.info(f"[步骤5-ETC结算数据处理] 处理ETC结算数据耗时: {end_time - start_time:.2f}秒")
    return response

# 封装函数，类似Dify服务
async def call_etc_sett_service(
    user_query: str, 
    phone_number: str, 
    conversation_id: Optional[str] = None, 
    debug: bool = False, 
    include_analysis: Optional[bool] = None, 
    include_chart: Optional[bool] = None, 
    is_monitor: bool = False,
    params: Optional[dict] = None
) -> dict:
    """调用ETC结算服务的封装函数
    
    Args:
        user_query: 用户查询
        phone_number: 手机号
        conversation_id: 对话ID
        debug: 是否开启调试模式
        include_analysis: 是否包含分析
        include_chart: 是否包含图表
        is_monitor: 是否为监控模式
        params: 外部传入的参数，如果不指定则自动提取
    """
    # 构建params参数
    if params is None:
        params = {
            "debug": debug,
            "is_monitor": is_monitor,
            "timeout": 60
        }
    else:
        # 更新默认参数
        params.update({
            "debug": debug,
            "is_monitor": is_monitor,
            "timeout": params.get("timeout", 60)
        })
    
    return await call_etc_service_common(
        user_id=phone_number,
        user_query=user_query,
        params=params,
        process_func=process_etc_sett_data,
        conversation_id=conversation_id,
        include_analysis=include_analysis,
        include_chart=include_chart,
        service_name="ETC结算"
    )